<template>
	<!-- 登录 -->
	<uni-popup ref="popupRef" type="bottom" :safe-area="false">
		<view class="get-phone-number">
			<view class="gn-top">
				<view class="left">
					<image class="img" :src="pageData.logo"></image> {{pageData.subjectName}}申请
				</view>
				<image class="right" :src="pageData.sigh" mode="widthFix"></image>
			</view>
			<view class="content-text">
				<!-- #ifdef MP-WEIXIN -->
				<text
					v-if="!pageData.wx.userPhone.iv&&pageData.isGetPhoneNumber">{{pageData.subjectName}}申请获取您绑定的手机号码,进行用户登录</text>
				<text
					v-else-if="pageData.wx.userPhone.iv||!pageData.isGetPhoneNumber">{{pageData.subjectName}}申请获取您的基本信息(头像,昵称),进行用户登录</text>
				<!-- #endif -->

			</view>
			<view class="btns">
				<button class="btn btn1" @click="tapCancel">
					取消
				</button>
				<!-- #ifdef MP-WEIXIN -->
				<button v-if="!pageData.wx.userPhone.iv&&pageData.isGetPhoneNumber" class="btn btn2"
					open-type="getPhoneNumber" @tap="close" @getphonenumber="getPhoneNumber">
					接受
				</button>
				<button v-else-if="pageData.wx.userPhone.iv||!pageData.isGetPhoneNumber" class="btn btn2"
					@tap="getUserInfo">
					接受
				</button>
				<!-- #endif -->

			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import { commUrl,appID } from '@/config/common';
	import {
		mainStore
	} from '@/store/index.js';
	import {
		reactive,
		ref
	} from 'vue'
	const emit = defineEmits(['success', 'fail'])
	let pageData = reactive({
		//请求的域名（服务器的地址）
		baseUrl:commUrl,
		//请求的API地址 
		urls: [
			"/sanitation/v1/login", //微信登录请求url
		],
		//申请授权的主体名称
		subjectName: "环保卫士",
		//申请主体的logo 1:1 的比例的图片
		logo: "./../../static/logo.png",
		// 叹号base64图片
		sigh: "",

		//登录时是否同时获取手机号0:不获取, 1:获取, 2:只获取手机号
		isGetPhoneNumber: 1,
		//---登录信息保存------------------------
		userInfo:{},
		header:{},
		wx: {
			userPhone: {
				encryptedData: '',
				iv: ''
			},
			user: {
				encryptedData: '',
				iv: '',
				rawData: '',
				signature: '',
				userInfo: {}
			},
			code: "",
			userInfo: ""
		},
	})
	const popupRef = ref(null)
	const open = (v = 1) => {
		pageData.isGetPhoneNumber = v
		//防止第二次调用的时候获取用户信息点击不了
		pageData.isGetInfoing = false
		uni.showLoading({
			mask: true
		})
		getCode(() => {
			uni.hideLoading()
			popupRef.value.open()
		}, () => {
			uni.hideLoading()
		})
	}
	const toast = (title, icon = "none", duration = 2000) => {
		uni.showToast({
			icon,
			title,
			duration
		})
	}
	// ---登录----------------------
	const close = (v) => {
		popupRef.value.close()
	}
	//取消授权
	const tapCancel = () => {
		clearUserInfo()
		close()
	}
	//获取微信登录授权code
	const getCode = async (callback, errfunc) => {
		try{
			let code =  await mainStore().login()
			pageData.wx.code = code
			if (callback) callback()
		}catch(e){
			toast("登录授权失败")
			if (errfunc) errfunc()
		}
		
	}
	const clearUserInfo = () => {
		//#ifdef MP-WEIXIN
		let arr = ['userPhone', 'user']
		for (let k of arr) {
			if (typeof pageData.wx[k] == 'Object') {
				for (let i in pageData.wx[k]) {
					if (i == 'userInfo') {
						pageData.wx[k][i] = {}
					} else {
						pageData.wx[k][i] = ''
					}
				}
			}
		}
		//#endif
	
	}
	//调用登录接口
	const toSign = () => {
		let url, data, method = 'post'
		// #ifdef MP-WEIXIN
		url = pageData.urls[0]
		/*
			微信的登录请求参数
		*/
		data = {
			code: pageData.wx.code,
			encryptedDataMobile: pageData.wx.userPhone.encryptedData,
			ivMobile: pageData.wx.userPhone.iv,
			encryptedData: pageData.wx.user.encryptedData,
			iv: pageData.wx.user.iv,
			rawData: pageData.wx.user.rawData,
			signature: pageData.wx.user.signature,
			appID:appID
		}

		if (!pageData.wx.code || !pageData.wx.userPhone.iv && pageData.isGetPhoneNumber || !pageData.wx.user.iv) {
			pageData.toast(!pageData.wx.code || !pageData.wx.user.iv ? "授权信息获取失败,请重新授权" : "手机号获取失败,请重新授权")
			pageData.clearUserInfo()
			setTimeout(() => {
				open()
			}, 100)
			return
		}


		for (let k in data) {
			if (data[k] === null || data[k] === undefined || data[k] === "") {
				delete data[k]
			}
		}
		// #endif

		if (!pageData.isGetPhoneNumber) {
			//不获取手机号把所有关与手机号的字段都删除掉
			delete data.encryptedDataMobile
			delete data.ivMobile
			delete data.mobileEncrypt
		}
		//拷贝保存到header以防setSignature中赋值时出现新增属性时响应式不响应的问题
		let header = JSON.parse(JSON.stringify(pageData.header))
		//如果请求有签名在setSignature中放入或调用您的签名方法
		setSignature(data, header)
		//请求方法############################################################################################### 
		request({
			url,
			data,
			method,
			header,
		})
	}
	//生成请求签名 
	const setSignature = (data, header) => {
		/*
			签名在data中上传直接赋值到data中即可如：
			data["sign"] = "8jfh8wru8wrun8w9w8ec334v"
			
			签名在header中上传直接赋值到header中即可如：
			header["sign"] = "8jfh8wru8wrun8w9w8ec334v"
		*/


	}
	//登录请求
	const request = (option) => {
		uni.request({
			//请求路径
			url: pageData.baseUrl + option.url,
			//请求方法
			method: option.method.toUpperCase(),
			//请求数据
			data: option.data,
			//请求头
			header: option.header,
			success: (res) => {
				uni.hideLoading()
				pageData.isGetInfoing = false
				if (res.statusCode == 200) {
					console.log("请求成功有数据返回但是也可能失败",res.data.token)
					//这里请求是成功了但是需要在父组件根据自己服务器返回的数据来判断是否登录成功
					//向上父组件发送数据（触发父组件的事件）
					uni.setStorageSync('token',res.data.token);
					mainStore().token = res.data.token
					emit("success", {
						//请求返回的信息
						result: res.data,
						//用户的信息
						userInfo: pageData.userInfo,
					})
					mainStore().setUserInfo(res.data)
					mainStore().getUserInfo()
					clearUserInfo()
				} else {
					console.log("请求错误")
					toast("登录失败!")
					emit("fail", false)
					clearUserInfo()
				}
			},
			fail: (err) => {
				console.log(err)
				uni.hideLoading()
				pageData.isGetInfoing = false
				toast("登录失败!")
				emit("fail", false)
				clearUserInfo()
			}
		})
	}
	//获取手机号
	const getPhoneNumber = (arg) => {
		if (pageData.isGetPhoneNumber == 2) {
			tapCancel()
			emit("getPhoneNumber", arg.detail)
		} else {
			pageData.wx.userPhone.encryptedData = arg.detail.encryptedData
			pageData.wx.userPhone.iv = arg.detail.iv
			mainStore().setUserInfo({userPhone:arg.detail})
			//成功获取手机号后打开获取用户信息弹窗
			popupRef.value.open()
		}

	}

	const getUserInfo = (val) => { //微信获取用户信息
		if (pageData.isGetInfoing) return
		pageData.isGetInfoing = true
		uni.getUserProfile({
			desc: "获取你的昵称、头像、地区及性别",
			success: (res) => {
				uni.showLoading({
					mask: false
				})
				pageData.wx.user.encryptedData = res.encryptedData
				pageData.wx.user.iv = res.iv
				pageData.wx.user.rawData = res.rawData
				pageData.wx.user.signature = res.signature
				pageData.wx.user.userInfo = res.userInfo
				//用户信息不包含手机号，手机号需要后端返回
				pageData.userInfo = JSON.parse(JSON.stringify(res.userInfo))
				mainStore().setUserInfo(pageData.userInfo)
				toSign()
				close()
			},
			fail: (e) => {
				pageData.isGetInfoing = false
				toast("用户信息获取失败")
				close()
			}
		})
	}




	defineExpose({
		open
	})






	
</script>

<style lang="scss" scoped>
	.get-phone-number {
		width: 100%;
		height: 540rpx;
		box-sizing: border-box;
		padding: 54rpx 36rpx;
		background-color: #ffffff;
		border-radius: 30rpx 30rpx 0 0;

		.gn-top {
			width: 100%;
			height: 56rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-weight: 400;
			font-size: 32rpx;
			color: #333333;
			margin-bottom: 32rpx;

			.left {
				display: flex;
				justify-content: flex-start;
				align-items: center;

				.img {
					width: 56rpx;
					height: 56rpx;
					border-radius: 6rpx;
					margin-right: 24rpx;
				}
			}

			.right {
				width: 32rpx;
				height: 32rpx;
			}
		}

		.content-text {
			width: 100%;
			box-sizing: border-box;
			padding: 12rpx 0;
			min-height: 80rpx;
			line-height: 40rpx;
			font-weight: 400;
			font-size: 32rpx;
			text-align: justify;
			color: #333333;
			margin-bottom: 100rpx;
		}

		.btns {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;

			.btn {
				width: 240rpx;
				height: 80rpx;
				border-radius: 16rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: 400;
				font-size: 30rpx;
				background: rgba(242, 242, 242, 1);
				margin: 0 auto;
				border: 0;

				&::after {
					border: 0;
				}
			}

			.btn1 {
				color: #07C160;
			}

			.btn2 {
				color: #FFFFFF;
				background: rgba(7, 193, 96, 1);
			}
		}
	}
</style>